using System;
using System.ComponentModel;
using System.Management;
using RollManager.Library.Utils;

namespace RollManager.Library.ActionSteps
{
    [Serializable]
    public class CheckServiceStep : ActionStep
    {
        public string m_serviceName = StepConstants.NAME;

        [DisplayName("Service Name")]
        [Description("The name of the service to be checked.")]
        public string ServiceName
        {
            get
            {
                return m_serviceName;
            }
            set
            {
                if( string.IsNullOrEmpty( value ) )
                {
                    throw new ArgumentException( "Service Name cannot be empty." );
                }
                else
                {
                    m_serviceName = value.Trim();
                }
            }
        }

        public override string Name
        {
            get { return "Check Service"; }
        }

        protected override void Run()
        {
            ManagementObject obj = getObject();

            // Make sure the service is running.
            string state = (string) obj[ "State" ];
            if( state == "Running" )
            {
                Progress.AddFormat( "{0} is running.", m_serviceName );
            }
            else 
            {
                throw new Exception( string.Format( "{0} has the status of {1}", m_serviceName, state ) );
            }
        }

        protected override void Simulate()
        {
            getObject();

            Progress.AddFormat( "Simulated checking of {0} on {1}.", m_serviceName, CurrentServer );
        }

        private ManagementObject getObject()
        {
            return Common.GetWmiObject( @"\\{0}\root\cimv2", CurrentServer, "Win32_Service", m_serviceName );
        }
    }
}
